<template>
    <view class="overall">
        <view class="tabs">
            <view 
                v-for="tab in tabs" 
                :key="tab.value"
                class="tab-item"
                :class="{ active: status === tab.value }"
                @click="state(tab.value)"
            >
                {{ tab.label }}
            </view>
        </view>
        <view class="content">
            <view class="orders" v-for="(item,index) in logsInfo" :key="index">
                <view class="ordersTitle">
                    <view>预约信息</view>
                    <view>{{
                        item.status==1?'待审核':
                        item.status==2?'审核通过':
                        item.status==3?'已就诊':
                        item.status==4?'驳回':
                        item.status==5?'已取消':''
                    }}</view>
                </view>
                <view class="ordersContent">
                    <view class="list">
                        <view>医生名称</view>
                        <view>{{item.doctor_name}}</view>
                    </view>
                    <view class="list">
                        <view>专科名称</view>
                        <view>{{item.depart_name}}</view>
                    </view>
                    <view class="listText">
                        <view>文字描述</view>
                        <view>
                            <text>{{item.trends}}</text>
                        </view>
                    </view>
                    <view class="listImage">
                        <view>病史图片</view>
                        <view class="image-container">
                            <!-- 使用image组件显示图片，添加点击事件实现预览 -->
                            <image 
                                v-for="(img, index) in item.img" 
                                :key="index"
                                :src="img.url" 
                                mode="aspectFit"
                                @error="handleImageError(item.img, index)"
                                @click="previewImage(item.img, index)"
                            />
                            <!-- 没有图片时显示提示 -->
                            <view v-if="!item.img || item.img.length === 0" class="no-image">
                                暂无病史图片
                            </view>
                        </view>
                    </view>
                    <view class="listAudio">
                        <view>录音</view>
                        <view>
                            <image 
                                @click="toggleAudio(item)" 
                                :src="getAudioIcon(item)" 
                                mode=""
                            />
                        </view>
                    </view>
                </view>
                <view class="listButton">
                    <view @click="del(item.status,item.id)">删除记录</view>
                    <view @click="edit(item.status,item.id)">取消预约</view>
                </view>
            </view>
            <wd-status-tip v-if="logsInfo.length==0?true:false" image="content" tip="暂无内容" />
        </view>
        <wd-popup v-model="show" position="top" custom-style=" min-height: 450rpx;">
        </wd-popup>
    </view>
</template>

<script lang="ts" setup>
    import { ref, reactive, onUnmounted } from 'vue';
    import { registerlogs, logsEdit, logsDel } from '/api/index.js';
    import { BASE_API_URL } from '@/utils/config'; // 导入配置
    
    // 新增 tabs 数据
    const tabs = [
        { label: '全部', value: 0 },
        { label: '待审核', value: 1 },
        { label: '审核通过', value: 2 },
        { label: '已就诊', value: 3 },
        { label: '驳回', value: 4 },
        { label: '已取消', value: 5 }
    ];
    
    const show = ref(false);
    const status = ref(1);
    const currentPlaying = ref(null); // 记录当前正在播放的音频ID
    const backgroundAudioManager = uni.getBackgroundAudioManager();

    function handleClickLeft() {
        uni.navigateBack();
    }

    const logsInfo = ref([]);
    const logsTow = ref([]);
    const userInfo = ref([]);

    async function fun() {
        try {
            const res = await uni.getStorage({ key: 'user' });
            const userId = res.data?.data?.id;
            const response = await registerlogs({ user_id: userId });
            
            if (response.data !== null) {
                const updatedData = response.data.map(item => {
                    // 处理图片数据
                    if (item.img) {
                        // 确保img是数组
                        const imgArray = typeof item.img === 'string' ? 
                            (item.img.includes(',') ? item.img.split(",") : [item.img]) : 
                            [];
                        
                        item.img = imgArray
                            .filter(url => url.trim()) // 过滤空值
                            .map(url => ({
                                url: url.startsWith('http') ? url : `${BASE_API_URL}${url}`
                            }));
                    } else {
                        item.img = [];
                    }
                    
                    // 为每个记录添加音频播放状态
                    item.audioPlaying = false;
                    
                    return item;
                });
                
                logsInfo.value = updatedData;
                logsTow.value = updatedData;
            }
        } catch (error) {
            console.error('获取日志列表出错:', error);
        }
    }
    
    fun();
    
    // 图片预览功能
    function previewImage(images, index) {
        // 提取所有图片的URL组成数组
        const urls = images.map(img => img.url);
        // 调用uni的图片预览API
        uni.previewImage({
            current: index,  // 当前显示图片的索引
            urls: urls,      // 需要预览的图片URL列表
            loop: true,      // 是否可循环预览
            indicator: 'default'  // 显示默认指示器
        });
    }
    
    function handleImageError(images, errorIndex) {
        console.log('图片加载失败，尝试替换为其他有效图片');
        
        // 查找当前记录中的其他有效图片
        const validImages = images.filter((img, index) => index !== errorIndex && img.loaded !== false);
        
        if (validImages.length > 0) {
            // 从有效图片中随机选择一张进行替换
            const randomValidImage = validImages[Math.floor(Math.random() * validImages.length)];
            images[errorIndex].url = randomValidImage.url;
            images[errorIndex].loaded = false; // 标记为已替换，避免循环替换
            console.log('已替换为其他有效图片');
        } else {
            console.log('没有其他有效图片可供替换');
            // 如果没有其他有效图片，使用默认图片
            images[errorIndex].url = '/static/default.png';
        }
    }
    
    // 获取音频图标（根据播放状态决定显示哪个图标）
    function getAudioIcon(item) {
        return item.audioPlaying ? '/static/pause.png' : '/static/video.png';
    }
    
    // 切换音频播放状态
    function toggleAudio(item) {
        // 如果点击的是正在播放的音频，则暂停
        if (currentPlaying.value === item.id) {
            backgroundAudioManager.pause();
            item.audioPlaying = false;
            currentPlaying.value = null;
            console.log('音频已暂停');
            return;
        }
        
        // 否则，先停止当前播放的音频
        if (currentPlaying.value) {
            const currentItem = logsInfo.value.find(i => i.id === currentPlaying.value);
            if (currentItem) {
                currentItem.audioPlaying = false;
            }
            backgroundAudioManager.stop();
        }
        
        // 播放新音频
        console.log('播放音频:', item.audio);
        backgroundAudioManager.src = `${BASE_API_URL}${item.audio}`;
        backgroundAudioManager.title = '音频';
        backgroundAudioManager.coverImgUrl = '/static/play.png';
        backgroundAudioManager.play();
        
        // 更新播放状态
        item.audioPlaying = true;
        currentPlaying.value = item.id;
        
        // 监听音频播放事件
        backgroundAudioManager.onPlay(() => {
            console.log('音频开始播放');
        });
        
        // 监听音频结束事件
        backgroundAudioManager.onEnded(() => {
            console.log('音频播放结束');
            item.audioPlaying = false;
            currentPlaying.value = null;
        });
        
        // 监听音频暂停事件
        backgroundAudioManager.onPause(() => {
            console.log('音频已暂停');
            if (currentPlaying.value === item.id) {
                item.audioPlaying = false;
                currentPlaying.value = null;
            }
        });
    }

    function sift() {
        show.value = true;
    }

    function state(i) {
        logsInfo.value = [];
        status.value = i;
        const arr = logsTow.value;
        
        if (i === 0) {
            logsInfo.value = logsTow.value;
        } else {
            logsInfo.value = arr.filter(item => item.status === i);
        }
    }

    async function del(status, id) {
        await fun();
        if (status !== 5) {
            uni.showModal({
                title: '提示',
                content: '该预约记录未取消，无法删除',
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    }
                }
            });
        } else {
            uni.showModal({
                title: '提示',
                content: '是否删除该记录',
                showCancel: true,
                success: async function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                        const response = await logsDel({ id: id });
                        console.log('删除记录响应:', response);
                        if (response.code === 1) {
                            logsInfo.value = [];
                            await fun();
                            uni.showToast({
                                title: '记录已删除',
                                icon: 'none'
                            });
                        } else {
                            uni.showToast({
                                title: '记录删除失败',
                                icon: 'none'
                            });
                        }
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        }
    }

    async function edit(status, id) {
        await fun();
        if (status === 5) {
            uni.showModal({
                title: '提示',
                content: '该预约记录已取消',
                showCancel: false,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    }
                }
            });
        } else {
            uni.showModal({
                title: '提示',
                content: '是否取消该记录',
                showCancel: true,
                success: async function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                        const response = await logsEdit({ id: id, status: 5 });
                        console.log('编辑记录响应:', response);
                        logsInfo.value = [];
                        await fun();
                        
                        // 新增：取消成功后跳转到"已取消"标签页
                        if (response.code === 1) {
                            state(5); // 切换到"已取消"标签页
                            uni.showToast({
                                title: '记录已取消',
                                icon: 'none'
                            });
                        } else {
                            uni.showToast({
                                title: '记录取消失败',
                                icon: 'none'
                            });
                        }
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        }
    }
    
    // 组件卸载时停止所有音频播放
    onUnmounted(() => {
        backgroundAudioManager.stop();
        if (currentPlaying.value) {
            const currentItem = logsInfo.value.find(i => i.id === currentPlaying.value);
            if (currentItem) {
                currentItem.audioPlaying = false;
            }
            currentPlaying.value = null;
        }
    });
</script>  


<style scoped>
    .overall {
        width: 100%;
        background-color: #F4F4F4;
        min-height: 100vh;
        padding-bottom: 500rpx;
    }

    .title {
        width: 100%;
        height: 180rpx;
        background-color: #00DACA;
        color: white;
        display: flex;
        align-items: center;
        position: fixed;
        top: 0;
        z-index: 100;
    }
    
    /* 新增标签页样式 */
    .tabs {
        display: flex;
        width: 100%;
        height: 80rpx;
        background-color: #fff;
        position: fixed;
        top: 0;
        z-index: 100;
        border-bottom: 1px solid #eee;
    }
    
    .tab-item {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 28rpx;
        color: #666;
    }
    
    .tab-item.active {
        color: #00DACA;
        font-weight: bold;
        position: relative;
    }
    
    .tab-item.active::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60%;
        height: 4rpx;
        background-color: #00DACA;
    }
    
    .name {
        display: flex;
        align-items: center;
        font-weight: bold;
        font-size: 42rpx;
        width: 35%;
        margin-top: 50rpx;
        margin-left: 3%;
    }

    .name>view {
        margin-left: 20rpx;
    }

    .content {
        margin-top: 100rpx;
    }
    
    .sift image {
        width: 35rpx;
        height: 35rpx;
        margin-right: 20rpx;
    }

    .sift {
        width: 94%;
        display: flex;
        background-color: white;
        padding: 30rpx 3%;
        align-items: center;
        justify-content: space-between;
    }

    .sift>view {
        display: flex;
        align-items: center;
        font-weight: bold;
        font-size: 32rpx;
    }

    .orders {
        width: 100%;
        min-height: 30vh;
        margin-top: 10rpx;
    }

    .ordersTitle {
        width: 92%;
        padding: 18rpx 4%;
        margin-bottom: 5rpx;
        background-color: white;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: bold;
    }

    .ordersTitle>view:first-child {
        font-size: 32rpx;
    }

    .ordersTitle>view:last-child {
        font-size: 29rpx;
    }

    .ordersContent {
        margin-bottom: 5rpx;
        background-color: white;
        width: 92%;
        padding: 18rpx 4%;
    }

    .ordersContent>view {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 28rpx;
    }

    .list {
        padding: 16rpx 0;
    }

    .list>view {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .listButton {
        width: 100%;
        display: flex;
        justify-content: space-between;
    }

    .listButton>view {
        width: 49.9%;
        height: 120rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 28rpx;
        background-color: white;
    }

    .listButton>view:first-child {
        color: #FF5733;
    }

    .listText {
        width: 100%;
        margin-top: 10rpx;
    }

    .listText>view:first-child {
        width: 40%;
        white-space: nowrap;
    }

    .listText>view:last-child {
        width: 50%;
        min-height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: flex-end;
    }

    .listText>view:last-child>text {
        text-align: end;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        word-wrap: break-word;
        display: block;
        width: 200px;
    }

    .listImage {
        white-space: nowrap;
        position: relative;
        height: 180rpx;
		margin-left: -4%;
    }

    .listImage>view:last-child {
        width: 80%;
        display: flex;
        flex-wrap: nowrap;
        justify-content: flex-end;
        align-items: center;
        position: absolute;
        right: -2%;
        top: 15rpx;
    }

    .listAudio image {
        width: 80rpx;
        height: 80rpx;
        object-fit: cover;
    }

    .listAudio>view {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .top {
        width: 90%;
        top: 0;
        padding: 30rpx 5%;
        position: fixed;
    }

    .top>view:first-child {
        font-weight: bold;
        font-size: 36rpx;
    }

    .top>view:last-child {
        display: flex;
        width: 100%;
        justify-content: space-between;
        align-items: center;
        margin-top: 30rpx;
    }

    .top>view:last-child>view {
        background-color: #E5E5E5;
        width: 25%;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 60rpx;
        border-radius: 10rpx;
    }

    /* 上传图片大小 */
    /deep/.wd-upload__preview.data-v-7c014dc0 {
        width: var(--wot-upload-size, 140rpx);
        height: var(--wot-upload-size, 140rpx);
    }
    
    .listImage {
        margin-bottom: 5rpx;
        background-color: white;
        padding: 18rpx 4%;
    }

    .image-container {
        display: flex;
        flex-wrap: wrap;
        gap: 10rpx;
        margin-top: 10rpx;
    }

    .image-container image {
        width: 140rpx;
        height: 140rpx;
        border-radius: 8rpx;
        border: 1px solid #eee;
		margin-right: 20px;

    }

    .no-image {
        color: #999;
        font-size: 24rpx;
        padding: 20rpx 0;
    }
</style>    